<!-- src/views/admin/RolePermissions.vue -->
<template>
  <div class="role-permissions-container">
    <div class="page-header">
      <h2>角色权限管理</h2>
      <p class="subtitle">管理系统角色的权限分配</p>
    </div>

    <el-card class="role-permissions-card" :body-style="{ padding: '20px' }">
      <!-- 1. 角色列表 -->
      <el-table 
        v-loading="loadingRoles" 
        :data="roles" 
        stripe 
        class="role-table"
        highlight-current-row
      >
        <el-table-column align="center" prop="id" label="角色 ID" width="100">
          <template #default="{ row }">
            <el-tag size="small" effect="plain" class="role-id-tag">
              {{ row.id }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="角色名称">
          <template #default="{ row }">
            <div class="role-name">
              <el-icon><UserFilled /></el-icon>
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="description" label="角色描述" />
        <el-table-column align="center" label="操作" width="180">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              class="detail-btn"
              @click="toggleRole(row)"
            >
              <el-icon>
                <ArrowUp v-if="currentRole?.id === row.id" />
                <ArrowDown v-else />
              </el-icon>
              {{ currentRole?.id === row.id ? "收起" : "详情" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 2. 分配区 -->
      <div v-if="currentRole" class="assign-section">
        <div class="assign-header">
          <h3>
            <el-icon><Setting /></el-icon>
            为角色 "{{ currentRole.name }}" 分配权限
          </h3>
          <p class="assign-description">{{ currentRole.description }}</p>
        </div>

        <div class="tags-container">
          <el-tooltip
            v-for="perm in allPermissions"
            :key="perm.id"
            :content="perm.description || '无描述'"
            placement="top"
            effect="dark"
          >
            <el-tag
              :type="checkedPermIds.includes(perm.id) ? 'success' : 'info'"
              @click="togglePerm(perm.id)"
              disable-transitions
              class="perm-tag"
              :class="{ 'is-selected': checkedPermIds.includes(perm.id) }"
            >
              <el-icon v-if="checkedPermIds.includes(perm.id)"><Check /></el-icon>
              {{ perm.name }}
            </el-tag>
          </el-tooltip>
        </div>

        <div class="assign-actions">
          <el-button 
            size="small" 
            class="action-btn"
            @click="toggleAll"
          >
            <el-icon>
              <Close v-if="isAllSelected" />
              <Check v-else />
            </el-icon>
            {{ isAllSelected ? "取消全选" : "全选权限" }}
          </el-button>
          <el-button 
            size="small" 
            class="action-btn"
            @click="clearSelection"
          >
            <el-icon><Delete /></el-icon>
            清空选择
          </el-button>
          <el-button 
            type="primary" 
            :loading="saving" 
            class="save-btn"
            @click="savePermissions"
          >
            <el-icon><Check /></el-icon>
            保存分配
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { 
  UserFilled, 
  Setting, 
  Check, 
  Close, 
  Delete,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue';
import { listAllRoles } from "@/api/userRoles";
import {
  listAllPermissions,
  getRolePermissions,
  assignPermissions,
} from "@/api/rolePermissions";

// 角色列表
const roles = ref([]);
const loadingRoles = ref(false);

// 权限列表 & 当前选中角色
const allPermissions = ref([]);
const currentRole = ref(null);
const checkedPermIds = ref([]);

// 控制按钮状态
const saving = ref(false);

// 是否全选
const isAllSelected = computed(() => {
  return (
    allPermissions.value.length > 0 &&
    checkedPermIds.value.length === allPermissions.value.length
  );
});

// 加载所有角色
async function loadRoles() {
  loadingRoles.value = true;
  try {
    const res = await listAllRoles({ pageNum: 1, pageSize: 100 });
    roles.value = res.data.items;
  } finally {
    loadingRoles.value = false;
  }
}

// 加载所有权限
async function loadAllPermissions() {
  const res = await listAllPermissions();
  allPermissions.value = res.data.items || res.data;
}

// 切换角色详情（同一个角色则折叠）
async function toggleRole(role) {
  if (currentRole.value?.id === role.id) {
    currentRole.value = null;
    checkedPermIds.value = [];
    return;
  }
  currentRole.value = role;
  saving.value = true;
  try {
    const res = await getRolePermissions(role.id);
    const perms = res.data.permissionIds || res.data;
    checkedPermIds.value = Array.from(perms);
  } finally {
    saving.value = false;
  }
}

// 切换单个权限
function togglePerm(pid) {
  const idx = checkedPermIds.value.indexOf(pid);
  if (idx >= 0) {
    checkedPermIds.value.splice(idx, 1);
  } else {
    checkedPermIds.value.push(pid);
  }
}

// 全选 / 取消全选
function toggleAll() {
  if (isAllSelected.value) {
    checkedPermIds.value = [];
  } else {
    checkedPermIds.value = allPermissions.value.map((p) => p.id);
  }
}

// 清空选择
function clearSelection() {
  checkedPermIds.value = [];
}

// 保存分配
async function savePermissions() {
  if (!currentRole.value) return;
  saving.value = true;
  try {
    await assignPermissions({
      roleId: currentRole.value.id,
      permissionIds: checkedPermIds.value,
    });
    ElMessage.success("权限分配成功");
  } finally {
    saving.value = false;
  }
}

// 初始加载
onMounted(async () => {
  await Promise.all([loadRoles(), loadAllPermissions()]);
});
</script>

<style scoped>
.role-permissions-container {
  padding: 24px;
  background-color: #f6f8fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  color: #1f2937;
  margin: 0;
}

.subtitle {
  color: #6b7280;
  margin: 8px 0 0;
}

.role-permissions-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.role-permissions-card:hover {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.role-table {
  margin-bottom: 32px;
  border-radius: 8px;
  overflow: hidden;
}

.role-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.role-table :deep(.el-table__row:hover) {
  background-color: #f9fafb !important;
}

.role-id-tag {
  font-family: monospace;
  font-size: 13px;
}

.role-name {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #374151;
}

.detail-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s ease;
}

.detail-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(99, 102, 241, 0.2);
}

.assign-section {
  margin-top: 32px;
  padding: 24px;
  background: #f9fafb;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

.assign-section:hover {
  background: #f3f4f6;
}

.assign-header {
  margin-bottom: 20px;
}

.assign-header h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  color: #1f2937;
  font-size: 18px;
}

.assign-description {
  margin: 8px 0 0;
  color: #6b7280;
  font-size: 14px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin: 20px 0;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  min-height: 64px;
}

.perm-tag {
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  font-size: 14px;
}

.perm-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.perm-tag.is-selected {
  font-weight: 500;
}

.assign-actions {
  margin-top: 24px;
  display: flex;
  gap: 16px;
  justify-content: flex-end;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
}

.save-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  min-width: 100px;
  transition: all 0.3s ease;
}

.save-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 6px rgba(99, 102, 241, 0.2);
}

@media (max-width: 900px) {
  .tags-container {
    gap: 8px;
    padding: 8px;
    font-size: 13px;
  }
  .assign-section {
    padding: 12px;
  }
}
@media (max-width: 600px) {
  .role-permissions-container {
    padding: 8px;
  }
  .role-permissions-card {
    padding: 0;
  }
  .assign-section {
    padding: 6px;
  }
  .tags-container {
    gap: 4px;
    padding: 4px;
    font-size: 12px;
  }
  .assign-actions {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
  